package com.bsc.minacommand.codec;

import com.bsc.minacommand.common.Constants;
import com.bsc.minacommand.model.AbstractBscCommand;
import org.apache.commons.lang.StringUtils;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

public class CommandEncoder extends ProtocolEncoderAdapter {

    public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
        AbstractBscCommand command = (AbstractBscCommand) message;
        //加入指令对象名称到流程中
         byte[] body = command.bodyToBytes();
        int commandNameLength = Constants.COMMAND_NAME_LENGTH;
        int len = commandNameLength + body.length;
        byte[] bytes = new byte[len];
        String name = StringUtils.rightPad(command.CommandName(), commandNameLength,
                Constants.COMMAND_NAME_PAD_CHAR);
        name = name.substring(0, commandNameLength);
        System.arraycopy(name.getBytes(), 0, bytes, 0, commandNameLength);
        System.arraycopy(body, 0, bytes, commandNameLength, body.length);

        //将要输出内容总长度加入流中
        IoBuffer buf = IoBuffer.allocate(bytes.length, false);
        buf.setAutoExpand(true);
        buf.putInt(bytes.length);
        buf.put(bytes);
        buf.flip();
        out.write(buf);
    }
}
